package com.ytjj.qmyx.data.amqp.consumer;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.rabbitmq.client.Channel;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.*;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.AliyunOSSClientUtil;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.qqzengip.IpSearch;
import com.ytjj.qmyx.data.model.AddressRequest;
import com.ytjj.qmyx.data.service.AppActivationService;
import com.ytjj.qmyx.mall.model.DynamicDto;
import com.ytjj.qmyx.mall.model.UserRegisterRequestDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *  *
 **/
@Slf4j
@Component
@RefreshScope
public class AppActivationListener {

    @Resource
    private AppActivationService appActivationService;
    @Autowired
    private RedisService redisService;
    @Resource
    private MongoTemplate mongoTemplate;
    @Value("${gaode.key:8ee7f00ac447f13f6f098491e446d6b4}")
    private String gaodeKey;
    /**
     * 根据ip解析地址方式
     * gaode=高德
     * local=本地地址库
     */
    @Value("${ip.type:gaode}")
    private String ipType;
    /**
     * ipType=local 时的源文件存放路径
     */
    @Value("${ip.sourcefile.path:}")
    private String ipSourceFilePath;

    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_ACTIVATION, durable = "true"))
    public void appActivation(String activationDtoStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
        log.debug("收到一条消息app_activation消息：" + activationDtoStr+"");
        AppDataStatisticsActivationDto activationDto = JSONObject.parseObject(activationDtoStr, AppDataStatisticsActivationDto.class);
        AddressRequest request = resloveAddressByIp(activationDto.getIp());
        if (null != request) {
            activationDto.setProvince(request.getProvince());
            activationDto.setCity(request.getCity());
            activationDto.setArea(request.getArea());
        }
        activationDto.setIp(doSubIpHandler(activationDto.getIp()));
        appActivationService.appActivation(activationDto);
    }

    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_USERACTIVE, durable = "true"))
    public void appUserAtive(String usersActiveDtoStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
        log.debug("收到一条消息app_user_active消息：" + usersActiveDtoStr+"");
        AppDataStatisticsUsersActiveDto usersActiveDto = JSONObject.parseObject(usersActiveDtoStr, AppDataStatisticsUsersActiveDto.class);
        AddressRequest request = resloveAddressByIp(usersActiveDto.getIp());
        if (null != request) {
            usersActiveDto.setProvince(request.getProvince());
            usersActiveDto.setCity(request.getCity());
            usersActiveDto.setArea(request.getArea());
        }
        usersActiveDto.setIp(doSubIpHandler(usersActiveDto.getIp()));
        appActivationService.appUserAtive(usersActiveDto);
    }

    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_USERBEHAVIOR, durable = "true"))
    public void appUserBehavior(AppDataStatisticsUsersBehaviorDto usersBehaviorDtoStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
        log.debug("收到一条消息app_user_behavior消息：" + usersBehaviorDtoStr+"");
        AppDataStatisticsUsersBehaviorDto usersBehaviorDto = usersBehaviorDtoStr;
        AddressRequest request = resloveAddressByIp(usersBehaviorDto.getIp());
        if (null != request) {
            usersBehaviorDto.setProvince(request.getProvince());
            usersBehaviorDto.setCity(request.getCity());
            usersBehaviorDto.setArea(request.getArea());
        }
        usersBehaviorDto.setIp(doSubIpHandler(usersBehaviorDto.getIp()));
        appActivationService.appUserBehavior(usersBehaviorDto);
    }

    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_USERREGISTER, durable = "true"))
    public void appUserRegister(String userRegisterDtoStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
        try {
            log.debug("收到一条消息app_user_register消息：{}", userRegisterDtoStr+"");
            UserRegisterRequestDto userRegisterDto = JSONObject.parseObject(userRegisterDtoStr, UserRegisterRequestDto.class);
            AddressRequest request = resloveAddressByIp(userRegisterDto.getIp());
            if (null != request) {
                userRegisterDto.setProvince(request.getProvince());
                userRegisterDto.setCity(request.getCity());
                userRegisterDto.setArea(request.getArea());
            }
            userRegisterDto.setIp(doSubIpHandler(userRegisterDto.getIp()));
            appActivationService.appUserRegister(userRegisterDto);
        } catch (Exception e) {
            log.info("====消费app_user_register消息异常：{}", e.getMessage());
            log.info("{}", e);
        }
    }

//    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.DYNAMIC_CHECK_PASS, durable = "true"))
//    public void dynamicCheckPass(String dynamicCheckPassStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
//        log.debug("收到一条消息dynamic_check_pass：{}", dynamicCheckPassStr);
//        DynamicDto dynamicDto = JSONObject.parseObject(dynamicCheckPassStr, DynamicDto.class);
//        appActivationService.dynamicCheckPass(dynamicDto);
//
//    }

//    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_EVALUATION_ADD, durable = "true"))
//    public void appEvaluationAdd(String appEvaluationStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
//        log.debug("收到一条消息app_evaluation_add：{}", appEvaluationStr);
//        DynamicDto dynamicDto = JSONObject.parseObject(appEvaluationStr, DynamicDto.class);
//        appActivationService.appEvaluationAdd(dynamicDto);
//
//    }

//    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_DYNAMICCOMMENT, durable = "true"))
//    public void appDynammicComment(String appDynamicCommentStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
//        log.debug("收到一条消息app_dynamiccomment：{}", appDynamicCommentStr);
//        DynamicCommentDto dynamicCommentDto = JSONObject.parseObject(appDynamicCommentStr, DynamicCommentDto.class);
//        appActivationService.appDynammicComment(dynamicCommentDto);
//    }

//    /**
//     * 点赞
//     * @param appDynamicLikeStr
//     * @param deliveryTag
//     * @param channel
//     */
//    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_DYNAMIC_LIKE, durable = "true"))
//    public void appDynammicLike(String appDynamicLikeStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
//        log.debug("收到一条消息app_dynamic_like：{}", appDynamicLikeStr);
//        DynamicLikeDto dynamicLikeDto = JSONObject.parseObject(appDynamicLikeStr, DynamicLikeDto.class);
//        appActivationService.appDynammicLike(dynamicLikeDto);
//    }

//    @RabbitListener(queuesToDeclare = @Queue(value = QueueConstants.APP_DYNAMIC_EXPOSURE, durable = "true"))
//    public void appDynamicExposure(String appDynamicExposureStr, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
//        log.debug("收到一条消息app_dynamic_exposure:{}", appDynamicExposureStr);
//        AppDataStatisticsExposureDto dynamicExposureDto = JSONObject.parseObject(appDynamicExposureStr, AppDataStatisticsExposureDto.class);
//        AddressRequest request = resloveAddressByIp(dynamicExposureDto.getIp());
//        if (null != request) {
//            dynamicExposureDto.setProvince(request.getProvince());
//            dynamicExposureDto.setCity(request.getCity());
//            dynamicExposureDto.setArea(request.getArea());
//        }
//        dynamicExposureDto.setIp(doSubIpHandler(dynamicExposureDto.getIp()));
//        appActivationService.appDynamicExposure(dynamicExposureDto);
//    }

    private String doSubIpHandler(String ip) {
        if (!StringUtils.isEmpty(ip)) {
            String[] ips = ip.split(",");
            if (ips.length > 0) {
                return ips[0];
            }
        }
        return "";
    }

    /**
     * 根据ip解析地址信息
     * @param ip
     * @return
     */
    private AddressRequest resloveAddressByIp(String ip) {
        AddressRequest addressRequest = new AddressRequest();
        if (StringUtils.isEmpty(ip)) {
            return addressRequest;
        }
        try {
            String ipAddressStrVal = redisService.getMapString("ip:address", ip);
            if (!StringUtils.isEmpty(ipAddressStrVal)) {
                addressRequest = JSONObject.parseObject(ipAddressStrVal, AddressRequest.class);
                if (null != addressRequest) {
                    return addressRequest;
                }
            }
        } catch (Exception e) {}

//        String addressByIp = AliyunOSSClientUtil.getAddressByIp(ip);
        //高德方式
//
        Map<String, String> hashMap = new HashMap();
        log.debug("===ipType==={}", ipType);
        if ("gaode".equals(ipType)) {
            //高德方式
            String addressByIp = IPUtil.getGaodeAddressByIdVersionOne(gaodeKey, ip);
            if(StringUtil.isEmpty(addressByIp)){
                return addressRequest;
            }
            hashMap = JSONObject.parseObject(addressByIp, HashMap.class);
            if (!"1".equals(hashMap.get("status"))) {
                return addressRequest;
            }
            if (!"OK".equals(hashMap.get("info"))) {
                return addressRequest;
            }
        } else if ("local".equals(ipType)) {
            //地址库方式
            if (StringUtils.isEmpty(ipSourceFilePath)) {
                ipSourceFilePath = "/mnt/ipsourcefile/qqzeng-ip-utf8.dat";
            }
            IpSearch finder = IpSearch.getInstance(ipSourceFilePath);
            String addressResult = finder.Get(ip);
            hashMap = IpSearch.analysisResult(addressResult);
        }

        String province = hashMap.get("province").toString();
        String city = hashMap.get("city").toString();
//        String area = hashMap.get("county").toString();
        String area = "";
        if(province.contains("重庆")){
            addressRequest.setProvince("重庆市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("万州区");
            return addressRequest;
        }
        if(province.contains("北京")){
            addressRequest.setProvince("北京市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("东城区");
            return addressRequest;
        }
        if(province.contains("天津")){
            addressRequest.setProvince("天津市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("和平区");
            return addressRequest;
        }
        if(province.contains("上海")){
            addressRequest.setProvince("上海市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("黄埔区");
            return addressRequest;
        }
        if(province.contains("台湾")){
            addressRequest.setProvince("台湾");
            addressRequest.setCity("台北");
            addressRequest.setArea("台北");
            return addressRequest;
        }
        if(province.contains("香港")){
            addressRequest.setProvince("香港");
            addressRequest.setCity("香港岛");
            addressRequest.setArea("香港岛");
            return addressRequest;
        }
        if(province.contains("澳门")){
            addressRequest.setProvince("澳门");
            addressRequest.setCity("澳门半岛");
            addressRequest.setArea("澳门半岛");
            return addressRequest;
        }
        if(province.contains("钓鱼")){
            addressRequest.setProvince("钓鱼岛");
            addressRequest.setCity("钓鱼岛");
            addressRequest.setArea("钓鱼岛全岛");
            return addressRequest;
        }
        addressRequest.setProvince(province);
        addressRequest.setCity(city);
        addressRequest.setArea(area);
        try {
            redisService.add("ip:address", ip, JSONObject.toJSONString(addressRequest));
        } catch (Exception e) {}
        try {
            mongoTemplate.save(addressRequest);
        } catch (Exception e) {}
        return addressRequest;
    }
}
